using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MVCWeekOne.Models;
using System.Text.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.ComponentModel;
using System.Reflection;
using System.Globalization;

namespace MVCWeekOne.Controllers
{
    public class TeamController : Controller
    {
        private readonly ApiSettings _apiSettings;
        private readonly HttpClient _httpClient;

        public TeamController(IOptions<ApiSettings> apiSettings, HttpClient httpClient)
        {
            _apiSettings = apiSettings.Value;
            _httpClient = httpClient;
        }

        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取班组分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetTeamPage(string teamName = "", string teamCode = "", string teamType = "", int index = 1, int size = 30)
        {
            try
            {
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(teamName)) queryParams.Add($"teamName={Uri.EscapeDataString(teamName)}");
                if (!string.IsNullOrEmpty(teamCode)) queryParams.Add($"teamCode={Uri.EscapeDataString(teamCode)}");
                if (!string.IsNullOrEmpty(teamType)) queryParams.Add($"teamType={Uri.EscapeDataString(teamType)}");
                queryParams.Add($"index={index}");
                queryParams.Add($"size={size}");

                                   var url = $"{_apiSettings.ReadApiUrl}/Team/GetTeamPage?{string.Join("&", queryParams)}";
                
                var response = await _httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    return Content(content, "application/json");
                }
                
                return Json(new { success = false, message = "获取数据失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取班组成员分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetTeamMemberPage(int? teamId = null, string memberName = "", string memberRealName = "", int index = 1, int size = 30)
        {
            try
            {
                var queryParams = new List<string>();
                if (teamId.HasValue) queryParams.Add($"teamId={teamId.Value}");
                if (!string.IsNullOrEmpty(memberName)) queryParams.Add($"memberName={Uri.EscapeDataString(memberName)}");
                if (!string.IsNullOrEmpty(memberRealName)) queryParams.Add($"memberRealName={Uri.EscapeDataString(memberRealName)}");
                queryParams.Add($"index={index}");
                queryParams.Add($"size={size}");

                                   var url = $"{_apiSettings.ReadApiUrl}/Team/GetTeamMemberPage?{string.Join("&", queryParams)}";
                
                var response = await _httpClient.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    return Content(content, "application/json");
                }
                
                return Json(new { success = false, message = "获取数据失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户分页数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAccountPage(string name = "", string realName = "", int index = 1, int size = 30)
        {
            try
            {
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(name)) queryParams.Add($"name={Uri.EscapeDataString(name)}");
                if (!string.IsNullOrEmpty(realName)) queryParams.Add($"realName={Uri.EscapeDataString(realName)}");
                queryParams.Add($"index={index}");
                queryParams.Add($"size={size}");

                var url = $"{_apiSettings.ReadApiUrl}/Account/GetAccountPage?{string.Join("&", queryParams)}";
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    return Content(content, "application/json");
                }

                return Json(new { success = false, message = "获取用户数据失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取用户数据失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取用户选择列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetAccountForSelection(string name = "", string realName = "", int index = 1, int size = 30)
        {
            try
            {
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(name)) queryParams.Add($"name={Uri.EscapeDataString(name)}");
                if (!string.IsNullOrEmpty(realName)) queryParams.Add($"realName={Uri.EscapeDataString(realName)}");
                queryParams.Add($"index={index}");
                queryParams.Add($"size={size}");

                var url = $"{_apiSettings.ReadApiUrl}/Account/GetAccountForSelection?{string.Join("&", queryParams)}";
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    return Content(content, "application/json");
                }

                return Json(new { success = false, message = "获取用户选择列表失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取用户选择列表失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 添加班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> AddTeam([FromBody] object teamData)
        {
            try
            {
                var url = $"{_apiSettings.WriteApiUrl}/Team/AddTeam";
                var json = System.Text.Json.JsonSerializer.Serialize(teamData);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return Content(responseContent, "application/json");
                }

                return Json(new { success = false, message = "添加班组失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"添加班组失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 删除班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteTeam([FromBody] object teamIds)
        {
            try
            {
                var url = $"{_apiSettings.WriteApiUrl}/Team/DeleteTeam";
                var json = System.Text.Json.JsonSerializer.Serialize(teamIds);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    return Content(responseContent, "application/json");
                }

                return Json(new { success = false, message = "删除班组失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"删除班组失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 获取班组详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetTeamDetail(int teamId)
        {
            try
            {
                var url = $"{_apiSettings.ReadApiUrl}/Team/GetTeamDetail?teamId={teamId}";
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();
                    return Content(content, "application/json");
                }

                return Json(new { success = false, message = "获取班组详情失败" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"获取班组详情失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 编辑班组
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateTeam([FromBody] object teamData)
        {
            try
            {
                var url = $"{_apiSettings.WriteApiUrl}/Team/UpdateTeam";
                
                // 将前端数据转换为后端期望的格式
                var jsonElement = System.Text.Json.JsonSerializer.SerializeToElement(teamData);
                
                // 处理班组成员数据
                var teamMembers = new List<object>();
                if (jsonElement.TryGetProperty("teamMembers", out var teamMembersProp) && teamMembersProp.ValueKind == System.Text.Json.JsonValueKind.Array)
                {
                    foreach (var member in teamMembersProp.EnumerateArray())
                    {
                        teamMembers.Add(new
                        {
                            Id = member.TryGetProperty("id", out var idProp) ? idProp.GetInt32() : 0,
                            AccountId = member.TryGetProperty("accountId", out var accountIdProp) ? accountIdProp.GetInt64() : 0L,
                            MemberName = member.TryGetProperty("memberName", out var memberNameProp) ? memberNameProp.GetString() : "",
                            MemberRealName = member.TryGetProperty("memberRealName", out var memberRealNameProp) ? memberRealNameProp.GetString() : "",
                            Phone = member.TryGetProperty("phone", out var phoneProp) ? phoneProp.GetString() : "",
                            IsDeleted = member.TryGetProperty("isDeleted", out var isDeletedProp) ? isDeletedProp.GetBoolean() : false
                        });
                    }
                }
                
                var updateCommand = new
                {
                    TeamId = jsonElement.TryGetProperty("teamId", out var teamIdProp) ? teamIdProp.GetInt32() : 0,
                    TeamName = jsonElement.TryGetProperty("teamName", out var teamNameProp) ? teamNameProp.GetString() : "",
                    TeamCode = jsonElement.TryGetProperty("teamCode", out var teamCodeProp) ? teamCodeProp.GetString() : "",
                    TeamType = jsonElement.TryGetProperty("teamType", out var teamTypeProp) ? teamTypeProp.GetInt32() : 0,
                    Remark = jsonElement.TryGetProperty("remark", out var remarkProp) ? remarkProp.GetString() : "",
                    TeamMembers = teamMembers
                };
                
                var json = System.Text.Json.JsonSerializer.Serialize(updateCommand);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
                
                // 添加调试日志
                Console.WriteLine($"发送到后端的JSON数据: {json}");
                
                var response = await _httpClient.PostAsync(url, content);

                // 添加响应调试信息
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"后端响应状态码: {response.StatusCode}");
                Console.WriteLine($"后端响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    return Content(responseContent, "application/json");
                }

                // 尝试解析错误信息
                try
                {
                    var errorResponse = System.Text.Json.JsonSerializer.Deserialize<dynamic>(responseContent);
                    var errorMessage = errorResponse?.GetProperty("msg")?.GetString() ?? "编辑班组失败";
                    return Json(new { success = false, message = errorMessage });
                }
                catch
                {
                    return Json(new { success = false, message = $"编辑班组失败: HTTP {response.StatusCode}" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"编辑班组异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { success = false, message = $"编辑班组失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 下载导入模板
        /// </summary>
        [HttpGet]
        public IActionResult DownloadTemplate()
        {
            try
            {
                using var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("班组导入模板");

                // 创建标题行样式
                var titleStyle = workbook.CreateCellStyle();
                var titleFont = workbook.CreateFont();
                titleFont.IsBold = true;
                titleFont.FontHeightInPoints = 12;
                titleStyle.SetFont(titleFont);
                titleStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
                titleStyle.BorderTop = BorderStyle.Thin;
                titleStyle.BorderBottom = BorderStyle.Thin;
                titleStyle.BorderLeft = BorderStyle.Thin;
                titleStyle.BorderRight = BorderStyle.Thin;

                // 创建标题行
                var headerRow = sheet.CreateRow(0);
                var headers = new[] { "班组名称", "编组编码", "班组类型", "备注" };

                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = headerRow.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = titleStyle;
                    sheet.SetColumnWidth(i, 15 * 256); // 设置列宽
                }

                // 添加说明行
                var noteRow = sheet.CreateRow(1);
                var noteCell = noteRow.CreateCell(0);
                noteCell.SetCellValue("说明：班组类型请填写：仓库、组装、机加工、注塑");
                var noteStyle = workbook.CreateCellStyle();
                var noteFont = workbook.CreateFont();
                noteFont.Color = IndexedColors.Red.Index;
                noteStyle.SetFont(noteFont);
                noteCell.CellStyle = noteStyle;

                // 输出到内存流
                using var ms = new MemoryStream();
                workbook.Write(ms, true);
                ms.Position = 0;

                return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "班组导入模板.xlsx");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"生成模板失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 导出班组数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportTeams(string teamName = "", string teamCode = "", string teamType = "")
        {
            try
            {
                // 获取所有数据（不分页）
                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(teamName)) queryParams.Add($"teamName={Uri.EscapeDataString(teamName)}");
                if (!string.IsNullOrEmpty(teamCode)) queryParams.Add($"teamCode={Uri.EscapeDataString(teamCode)}");
                if (!string.IsNullOrEmpty(teamType)) queryParams.Add($"teamType={Uri.EscapeDataString(teamType)}");
                queryParams.Add("index=1");
                queryParams.Add("size=10000"); // 获取大量数据

                var url = $"{_apiSettings.ReadApiUrl}/Team/GetTeamPage?{string.Join("&", queryParams)}";
                var response = await _httpClient.GetAsync(url);

                if (!response.IsSuccessStatusCode)
                {
                    return Json(new { success = false, message = "获取数据失败" });
                }

                var content = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<JsonElement>(content);

                if (!result.TryGetProperty("pageData", out var pageDataElement) || pageDataElement.ValueKind != JsonValueKind.Array)
                {
                    return Json(new { success = false, message = "数据格式错误" });
                }

                var teams = new List<TeamModel>();
                foreach (var item in pageDataElement.EnumerateArray())
                {
                    var team = new TeamModel
                    {
                        Id = GetStringSafe(item, "id"),
                        TeamName = GetStringSafe(item, "teamName"),
                        TeamCode = GetStringSafe(item, "teamCode"),
                        TeamType = MapTeamType(GetStringSafe(item, "teamType")),
                        Remark = GetStringSafe(item, "remark"),
                        Creator = GetStringSafe(item, "creator"),
                        CreateTime = item.TryGetProperty("createTime", out var createTimeElement) && createTimeElement.ValueKind != JsonValueKind.Null
                            ? ParseDateTime(createTimeElement)
                            : null,
                        Modifier = GetStringSafe(item, "modifier"),
                        ModifyTime = item.TryGetProperty("modifyTime", out var modifyTimeElement) && modifyTimeElement.ValueKind != JsonValueKind.Null
                            ? ParseDateTime(modifyTimeElement)
                            : null
                    };
                    teams.Add(team);
                }

                // 创建Excel文件
                using var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("班组数据");

                // 创建标题行样式
                var titleStyle = workbook.CreateCellStyle();
                var titleFont = workbook.CreateFont();
                titleFont.IsBold = true;
                titleFont.FontHeightInPoints = 12;
                titleStyle.SetFont(titleFont);
                titleStyle.FillForegroundColor = IndexedColors.Grey25Percent.Index;
                titleStyle.BorderTop = BorderStyle.Thin;
                titleStyle.BorderBottom = BorderStyle.Thin;
                titleStyle.BorderLeft = BorderStyle.Thin;
                titleStyle.BorderRight = BorderStyle.Thin;

                // 创建标题行
                var headerRow = sheet.CreateRow(0);
                var headers = new[] { "班组名称", "编组编码", "班组类型", "备注" };

                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = headerRow.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = titleStyle;
                    sheet.SetColumnWidth(i, 15 * 256);
                }

                // 添加数据行
                for (int i = 0; i < teams.Count; i++)
                {
                    try
                    {
                        var team = teams[i];
                        var dataRow = sheet.CreateRow(i + 1);
                        
                        dataRow.CreateCell(0).SetCellValue(team.TeamName ?? "");
                        dataRow.CreateCell(1).SetCellValue(team.TeamCode ?? "");
                        dataRow.CreateCell(2).SetCellValue(team.TeamType ?? "");
                        dataRow.CreateCell(3).SetCellValue(team.Remark ?? "");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error processing team at index {i}: {ex.Message}");
                        throw; // 重新抛出异常以便调试
                    }
                }

                // 输出到内存流
                using var ms = new MemoryStream();
                workbook.Write(ms, true);
                ms.Position = 0;

                var fileName = $"班组数据_{DateTime.Now:yyyyMMdd_HHmmss}.xlsx";
                return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"导出失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 导入班组数据
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> ImportTeams(IFormFile file)
        {
            var result = new TeamImportResult();

            try
            {
                if (file == null || file.Length == 0)
                {
                    result.Success = false;
                    result.Message = "请选择要导入的文件";
                    return Json(result);
                }

                if (!file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase))
                {
                    result.Success = false;
                    result.Message = "只支持.xlsx格式的Excel文件";
                    return Json(result);
                }

                if (file.Length > 100 * 1024 * 1024) // 100MB
                {
                    result.Success = false;
                    result.Message = "文件大小不能超过100MB";
                    return Json(result);
                }

                using var stream = file.OpenReadStream();
                using var workbook = new XSSFWorkbook(stream);
                var sheet = workbook.GetSheetAt(0);

                var teams = new List<TeamModel>();
                var errors = new List<string>();

                // 从第二行开始读取数据（第一行是标题）
                for (int i = 1; i <= sheet.LastRowNum; i++)
                {
                    var row = sheet.GetRow(i);
                    if (row == null) continue;

                    try
                    {
                        var team = new TeamModel
                        {
                            TeamName = GetCellValue(row.GetCell(0))?.Trim() ?? "",
                            TeamCode = GetCellValue(row.GetCell(1))?.Trim() ?? "",
                            TeamType = GetCellValue(row.GetCell(2))?.Trim() ?? "",
                            Remark = GetCellValue(row.GetCell(3))?.Trim() ?? ""
                        };

                        // 验证必填字段
                        if (string.IsNullOrEmpty(team.TeamName))
                        {
                            errors.Add($"第{i + 1}行：班组名称不能为空");
                            continue;
                        }

                        if (string.IsNullOrEmpty(team.TeamCode))
                        {
                            errors.Add($"第{i + 1}行：编组编码不能为空");
                            continue;
                        }

                        if (string.IsNullOrEmpty(team.TeamType))
                        {
                            errors.Add($"第{i + 1}行：班组类型不能为空");
                            continue;
                        }

                        // 验证班组类型
                        var validTypes = new[] { "仓库", "组装", "机加工", "注塑" };
                        if (!validTypes.Contains(team.TeamType))
                        {
                            errors.Add($"第{i + 1}行：班组类型必须是：仓库、组装、机加工、注塑");
                            continue;
                        }

                        teams.Add(team);
                    }
                    catch (Exception ex)
                    {
                        errors.Add($"第{i + 1}行：数据格式错误 - {ex.Message}");
                    }
                }

                if (teams.Count == 0)
                {
                    result.Success = false;
                    result.Message = "没有有效的数据可以导入";
                    result.Errors = errors;
                    return Json(result);
                }

                // 调用后端API批量添加
                var url = $"{_apiSettings.WriteApiUrl}/Team/BatchAddTeams";
                var importData = new { teams = teams };
                var json = JsonSerializer.Serialize(importData);
                var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var apiResult = JsonSerializer.Deserialize<JsonElement>(responseContent);

                    if (apiResult.TryGetProperty("code", out var codeElement) && codeElement.GetInt32() == 200)
                    {
                        result.Success = true;
                        result.Message = apiResult.TryGetProperty("msg", out var msgElement) 
                            ? msgElement.GetString() ?? "导入成功" 
                            : "导入成功";
                        
                        // 获取详细结果
                        if (apiResult.TryGetProperty("data", out var dataElement))
                        {
                            if (dataElement.TryGetProperty("totalCount", out var totalElement))
                                result.TotalCount = totalElement.GetInt32();
                            if (dataElement.TryGetProperty("successCount", out var successElement))
                                result.SuccessCount = successElement.GetInt32();
                            if (dataElement.TryGetProperty("failCount", out var failElement))
                                result.FailCount = failElement.GetInt32();
                            if (dataElement.TryGetProperty("errors", out var errorsElement) && errorsElement.ValueKind == JsonValueKind.Array)
                            {
                                foreach (var error in errorsElement.EnumerateArray())
                                {
                                    result.Errors.Add(error.GetString() ?? "");
                                }
                            }
                        }
                    }
                    else
                    {
                        result.Success = false;
                        result.Message = apiResult.TryGetProperty("msg", out var msgElement) 
                            ? msgElement.GetString() ?? "导入失败" 
                            : "导入失败";
                        
                        // 获取错误详情
                        if (apiResult.TryGetProperty("data", out var dataElement) && 
                            dataElement.TryGetProperty("errors", out var errorsElement) && 
                            errorsElement.ValueKind == JsonValueKind.Array)
                        {
                            foreach (var error in errorsElement.EnumerateArray())
                            {
                                result.Errors.Add(error.GetString() ?? "");
                            }
                        }
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "调用后端API失败";
                    result.Errors = errors;
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"导入失败: {ex.Message}";
                result.Errors.Add(ex.Message);
            }

            return Json(result);
        }

        /// <summary>
        /// 解析日期时间（支持字符串和数字类型）
        /// </summary>
        private DateTime? ParseDateTime(JsonElement element)
        {
            try
            {
                switch (element.ValueKind)
                {
                    case JsonValueKind.String:
                        var dateString = element.GetString();
                        if (string.IsNullOrEmpty(dateString))
                            return null;
                        return DateTime.Parse(dateString);
                    
                    case JsonValueKind.Number:
                        var timestamp = element.GetInt64();
                        // 判断时间戳是秒还是毫秒
                        if (timestamp > 1000000000000) // 大于这个值说明是毫秒
                        {
                            return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).DateTime;
                        }
                        else // 秒
                        {
                            return DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;
                        }
                    
                    default:
                        return null;
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常，返回null
                Console.WriteLine($"ParseDateTime error: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 安全获取字符串字段，兼容字符串/数字/布尔
        /// </summary>
        private string GetStringSafe(JsonElement obj, string propertyName)
        {
            if (!obj.TryGetProperty(propertyName, out var prop) || prop.ValueKind == JsonValueKind.Null)
            {
                return string.Empty;
            }

            try
            {
                switch (prop.ValueKind)
                {
                    case JsonValueKind.String:
                        return prop.GetString() ?? string.Empty;
                    case JsonValueKind.Number:
                        return prop.TryGetInt64(out var n)
                            ? n.ToString(CultureInfo.InvariantCulture)
                            : prop.GetDouble().ToString(CultureInfo.InvariantCulture);
                    case JsonValueKind.True:
                    case JsonValueKind.False:
                        return prop.GetBoolean().ToString();
                    default:
                        return prop.ToString();
                }
            }
            catch
            {
                return prop.ToString();
            }
        }

        /// <summary>
        /// 将后端返回的班组类型映射为中文（兼容数字/英文/中文）
        /// </summary>
        private string MapTeamType(string raw)
        {
            if (string.IsNullOrWhiteSpace(raw)) return string.Empty;
            // 统一化
            var v = raw.Trim();
            return v switch
            {
                "0" => "仓库",
                "1" => "组装",
                "2" => "机加工",
                "3" => "注塑",
                // 兼容可能的英文/中文输入
                "仓库" => "仓库",
                "组装" => "组装",
                "机加工" => "机加工",
                "注塑" => "注塑",
                "warehouse" => "仓库",
                "assembly" => "组装",
                "machining" => "机加工",
                "injection" => "注塑",
                _ => v
            };
        }

        /// <summary>
        /// 获取单元格值
        /// </summary>
        private string? GetCellValue(ICell? cell)
        {
            if (cell == null) return null;

            switch (cell.CellType)
            {
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Numeric:
                    if (DateUtil.IsCellDateFormatted(cell))
                    {
                        return cell.DateCellValue?.ToString("yyyy-MM-dd HH:mm:ss") ?? "";
                    }
                    return cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString(CultureInfo.InvariantCulture);
                case CellType.Formula:
                    return cell.StringCellValue;
                default:
                    return null;
            }
        }
    }
}
